<template>
  <!-- 登录页面的容器 -->
  <div class="login-container">
    <!-- 背景文本，显示实验名称 -->
    <div class="background-text">实验一：留言本系统</div>
    <!-- 登录卡片，使用element-ui的card组件 -->
    <el-card class="login-card">
      <!-- 使用tabs切换登录和注册功能 -->
      <el-tabs v-model="activeTab">
        <!-- 登录表单所在的tab -->
        <el-tab-pane label="登录" name="login">
          <!-- 登录表单，使用element-ui的form组件 -->
          <el-form @submit.prevent="login" :model="loginForm" :rules="loginRules" ref="loginFormRef">
            <!-- 用户名输入框 -->
            <el-form-item prop="username">
              <el-input v-model="loginForm.username" placeholder="用户名" prefix-icon="el-icon-user"></el-input>
            </el-form-item>
            <!-- 密码输入框 -->
            <el-form-item prop="password">
              <el-input v-model="loginForm.password" type="password" placeholder="密码" prefix-icon="el-icon-lock"></el-input>
            </el-form-item>
            <!-- 登录按钮 -->
            <el-form-item>
              <el-button type="primary" native-type="submit" :loading="loading" class="submit-button">登录</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <!-- 注册表单所在的tab -->
        <el-tab-pane label="注册" name="register">
          <!-- 注册表单，使用element-ui的form组件 -->
          <el-form @submit.prevent="register" :model="registerForm" :rules="registerRules" ref="registerFormRef">
            <!-- 用户名输入框 -->
            <el-form-item prop="username">
              <el-input v-model="registerForm.username" placeholder="用户名" prefix-icon="el-icon-user"></el-input>
            </el-form-item>
            <!-- 密码输入框 -->
            <el-form-item prop="password">
              <el-input v-model="registerForm.password" type="password" placeholder="密码" prefix-icon="el-icon-lock"></el-input>
            </el-form-item>
            <!-- 确认密码输入框 -->
            <el-form-item prop="confirmPassword">
              <el-input v-model="registerForm.confirmPassword" type="password" placeholder="确认密码" prefix-icon="el-icon-lock"></el-input>
            </el-form-item>
            <!-- 注册按钮 -->
            <el-form-item>
              <el-button type="primary" native-type="submit" :loading="loading" class="submit-button">注册</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>


<script>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage } from 'element-plus';

export default {
  name: 'LoginComponent',
  setup() {
    const router = useRouter();
    const loginFormRef = ref(null);
    const registerFormRef = ref(null);
    const loading = ref(false);
    const activeTab = ref('login');

    const loginForm = reactive({
      username: '',
      password: ''
    });

    const registerForm = reactive({
      username: '',
      password: '',
      confirmPassword: ''
    });

    const loginRules = {
      username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
      password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
    };

    const registerRules = {
      username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
      password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        { validator: (rule, value, callback) => {
          if (value !== registerForm.password) {
            callback(new Error('两次输入的密码不一致'));
          } else {
            callback();
          }
        }, trigger: 'blur' }
      ]
    };


  const login = async () => {
  if (!loginFormRef.value) return;

  await loginFormRef.value.validate(async (valid) => {
  if (valid) {
    loading.value = true;
    try {
      const response = await axios.post('/api/auth/login', loginForm);
      console.log('登录响应:', response.data);
      
      // 存储 token, userRole 和 username 到 localStorage
      localStorage.setItem('token', response.data.token);
      localStorage.setItem('userRole', response.data.role);
      localStorage.setItem('userId', response.data.id); // 确保存储 userId
      localStorage.setItem('username', response.data.username); // 存储 username

      ElMessage.success('登录成功');
      router.push('/guestbook');
    } catch (error) {
      console.error('登录失败:', error.response ? error.response.data : error.message);
      ElMessage.error(`登录失败: ${error.response ? error.response.data.message : error.message}`);
    } finally {
      loading.value = false;
    }
  }
  });
  };

    const register = async () => {
      if (!registerFormRef.value) return;

      await registerFormRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true;
          try {
            await axios.post('http://localhost:8080/api/users/register', {
              username: registerForm.username,
              password: registerForm.password
            });
            ElMessage.success('注册成功，请登录');
            activeTab.value = 'login';
          } catch (error) {
            console.error('注册失败:', error.response ? error.response.data : error.message);
            ElMessage.error(`注册失败: ${error.response ? error.response.data : error.message}`);
          } finally {
            loading.value = false;
          }
        }
      });
    };

    return {
      loginForm,
      registerForm,
      loginRules,
      registerRules,
      login,
      register,
      loginFormRef,
      registerFormRef,
      loading,
      activeTab
    };
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  width: 100%;
  background: linear-gradient(135deg, #357fca 0%, #8cc8d6 100%);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.login-card {
  width: 350px;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08);
  background-color: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
}

.submit-button {
  width: 100%;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-input {
  margin-bottom: 10px;
}

.background-text {
  position: absolute;
  top: 15%;
  left: 50%;
  transform: translateX(-50%);
  font-size: 36px;
  font-weight: bold;
  color: #000000;
  width: 100%;
  text-align: center;
  z-index: 1000;
}
</style>
